package com.zr.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zr.mapper.StudentMapper;
import com.zr.pojo.Student;
import com.zr.service.StudentService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Resource
    private StudentMapper mapper;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void add(Student student) {
        mapper.insert(student);
    }

    @Override
    public PageInfo<Student> selectByPage(Integer pageNum, Integer pageSize) {
        //利用PageHelper分页查询 注意：这个一定要放查询语句的前一行,否则无法进行分页,因为它对紧随其后第一个sql语句有效
        PageHelper.startPage(pageNum, pageSize);
        List<Student> empList = mapper.selectList(null);
        //5表示连续显示的页码数量
        PageInfo<Student> pageInfo = new PageInfo<>(empList,3);
        return pageInfo;
    }

    @Override
    public Student selectOne(Student student) {
        return mapper.selectOne(student);
    }

    @Override
    public String selectAll() {
//        Jedis jedis = JedisPoolUtils.getJedis();
//        String student = jedis.get("student");
//        if(student==null || student.length()==0){
//            List<Student> students = mapper.selectList(null);
//            ObjectMapper objectMapper=new ObjectMapper();
//            String s = null;
//            try {
//                s = objectMapper.writeValueAsString(students);
//            } catch (JsonProcessingException e) {
//                e.printStackTrace();
//            }
//            return s;
//        }
//        return student;

//        Object student = redisTemplate.opsForValue().get("student");
        long l11 = System.currentTimeMillis();
        String student = (String) redisTemplate.opsForValue().get("student");
        long l22 = System.currentTimeMillis();
        System.out.println(l22-l11+"redis");
        if(student==null || student.length()==0){
            long l1 = System.currentTimeMillis();
            List<Student> students = mapper.selectList(null);
            long l2 = System.currentTimeMillis();
            System.out.println(l2-l1+"sql");

            ObjectMapper objectMapper=new ObjectMapper();
            String s = null;
            try {
                s = objectMapper.writeValueAsString(students);
                redisTemplate.opsForValue().set("student",s);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return s;
        }
        return student;
    }


}
